/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.server;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/commonUpdate/{sessionId}")
@Component
@Slf4j
public class CommonUpdateServer {

    private static final int MAX_RETRY_SIZE = 3;
    private static final String PING = "ping";
    private static final String PONG = "pong";
    public static final String ALERT_MESSAGE_CHANGED = "{\"alertMessageChanged\":true}";
    /**
     * Store all connected sessions
     */
    private static Map<String, CommonUpdateServer> commonUpdateServers = new ConcurrentHashMap<>();
    /**
     * The connection session
     */
    private Session session;
    /**
     * The connection session id
     */
    private String sessionId = "";

    /**
     * Server send message to special client
     */
    public static void sendInfo(String message, @PathParam("sessionId") String sessionId) throws IOException {
        log.debug("websocket send :" + sessionId + "，message:" + message);
        if (StringUtils.hasText(sessionId) && commonUpdateServers.containsKey(sessionId)) {
            commonUpdateServers.get(sessionId).sendMessage(message);
        } else {
            log.error("page: {} offline！", sessionId);
        }
    }

    /**
     * Called after an opening handshake has been performed and the given websocket is ready to be written on.
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sessionId") String sessionId) {
        this.session = session;
        this.sessionId = sessionId;
        commonUpdateServers.computeIfAbsent(sessionId, key -> this);
        sendMessage("连接成功");
    }

    /**
     * Called after the websocket connection has been closed
     */
    @OnClose
    public void onClose() {
        commonUpdateServers.remove(sessionId);
        log.info("page out:{}", sessionId);
    }

    /**
     * Callback for string messages received from the client
     *
     * @param message client message
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (PING.equals(message)) {
            sendMessage(PONG);
        }
    }

    /**
     * Called when the session protocol error occurs.
     *
     * @param session The session.
     * @param error   The exception.
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("page error, session {},cause:{}", session, error.getMessage(), error);
    }

    /**
     * Server send message to client
     */
    public void sendMessage(String message) {
        boolean sendSuccess = false;
        for (int retry = 0; retry < MAX_RETRY_SIZE; retry++) {
            if (!sendSuccess) {
                try {
                    this.session.getBasicRemote().sendText(message);
                    sendSuccess = true;
                } catch (IOException e) {
                    log.error("send message error,session:{},message:{}", session, message);
                    ThreadUtil.sleep(100);
                }
            }

        }
    }

    /**
     * Server send message to all client
     */
    public static void sendMessageToAll(String message) {
        CommonUpdateServer.commonUpdateServers.forEach((sessionId, webSocket) -> webSocket.sendMessage(message));
    }

}
